package client

import (
	"bytes"
	"flag"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

var gatewayPath = flag.String("k", "http://localhost:8000", "the config Kong of admin api")

type (
	KongBasicHttp interface {
		SetHeader(H map[string]string)
		Do() (string, error)
		Get() (string, error)
		Post(body []byte) (string, error)
		PostForm(values url.Values) (string, error)
	}
	GatewayClient struct {
		Client  *http.Client
		Request *http.Request
	}
)

func NewGatewayClient(path string) (KongBasicHttp, error) {
	if strings.Compare(string(path[0]), "/") != 0 {
		path = "/" + path
	}
	request, _ := http.NewRequest("", *gatewayPath+path, nil)
	request.Header.Set("Accept-Encoding", "gzip, deflate, br")
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	return &GatewayClient{
		Client:  &http.Client{},
		Request: request,
	}, nil
}
func (g GatewayClient) SetHeader(H map[string]string) {
	for key, value := range H {
		g.Request.Header.Set(key, value)
	}
}
func (g GatewayClient) Do() (string, error) {
	response, err := g.Client.Do(g.Request)
	if err != nil {
		return "", err
	}
	body, _ := ioutil.ReadAll(response.Body)
	defer response.Body.Close()
	return string(body), nil
}
func (g GatewayClient) Get() (string, error) {
	g.Request.Method = "GET"
	return g.Do()
}
func (g GatewayClient) Post(body []byte) (string, error) {
	g.Request.Method = "POST"
	g.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
	return g.Do()
}
func (g GatewayClient) PostForm(values url.Values) (string, error) {
	g.Request.Method = "POST"
	resp, err := g.Client.PostForm(g.Request.URL.String(), values)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	return string(body), nil
}
